<template>
  <div id="globalHeader">
    <a-row :wrap="false">
      <a-col flex="200px">
        <router-link to="/">
          <div class="title-bar">
            <img class="logo" src="../assets/logo.png" alt="logo" />
            <div class="title">蜂云盒子</div>
          </div>
        </router-link>
      </a-col>
      <a-col flex="auto" class="menu-bar">
        <a-menu
          v-model:selectedKeys="current"
          mode="horizontal"
          :items="menuItems"
          @click="doMenuClick"
        />
      </a-col>
      <!-- 天气和位置信息 + 主题切换 -->
      <a-col class="weather-col" flex="520px">
        <div class="weather-theme-container">
          <WeatherLocation />
          <ThemeSwitcher />
        </div>
      </a-col>

      <!-- 用户信息展示栏 -->
      <a-col flex="130px">
        <div v-if="loginUserStore.loginUser.id" class="user-info">
          {{ loginUserStore.loginUser.userName ?? '默认用户名' }}
          <a-dropdown>
            <img
              :src="
                loginUserStore.loginUser.userAvatar
                  ? userAvatarPrefix + loginUserStore.loginUser.userAvatar
                  : '/src/assets/default_avatar.png'
              "
              alt="avatar"
              class="avatar"
            />
            <template #overlay>
              <a-menu>
                <a-menu-item key="0">
                  <router-link to="/user/profile">
                    <UserOutlined />
                    <span>个人中心</span>
                  </router-link>
                </a-menu-item>

                <a-menu-divider />
                <a-menu-item key="1" @click="handleLogout">
                  <LogoutOutlined />
                  <span>退出登录</span>
                </a-menu-item>

                <a-menu-item key="2" @click="handleDeleteAccount">
                  <DeleteOutlined />
                  <span style="color: #ff4d4f">注销账号</span>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-else>
          <router-link to="/user/login">
            <a-button type="primary" class="login-button">登录/注册</a-button>
          </router-link>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
  import { computed, h, ref } from 'vue' // 导入vue
  import { HomeOutlined, LogoutOutlined, UserOutlined, DeleteOutlined } from '@ant-design/icons-vue' // 导入图标
  import { message } from 'ant-design-vue' // 导入消息
  import { useRouter } from 'vue-router' // 导入路由
  import { useLoginUserStore } from '@/stores/useLoginUserStore'
  import { userLogoutUsingPost1 } from '@/api/yonghumokuaijiekou'
  import WeatherLocation from './WeatherLocation.vue' // 导入天气位置组件
  import ThemeSwitcher from './ThemeSwitcher.vue' // 导入主题切换组件

  const loginUserStore = useLoginUserStore()
  const userAvatarPrefix = 'https://fy-space-1333414113.cos.ap-beijing.myqcloud.com'

  // 过滤后的菜单项
  const menuItems = computed(() => {
    const isAdmin = loginUserStore.loginUser?.userRole === 'admin'

    // 基础菜单项
    const baseItems = [
      {
        key: '/',
        icon: () => h(HomeOutlined),
        label: '主页',
        title: '主页',
      },
      {
        key: '/user/personalSpace',
        label: '个人空间',
        title: '个人空间',
      },
      {
        key: '/user/createSource',
        label: '创建资源',
        title: '创建资源',
      },
      {
        key: '/team/space',
        label: '团队空间',
        title: '团队空间',
      },
      {
        key: '/intelligent/paradise',
        label: '智能天堂',
        title: '智能天堂',
      },
    ]

    // 管理员菜单项
    const adminItems = [
      {
        key: '/admin/pictureManage',
        label: '图片管理',
        title: '图片管理',
      },
      {
        key: '/admin/userManage',
        label: '用户管理',
        title: '用户管理',
      },
      {
        key: '/admin/unsplashPic',
        label: '资源图片',
        title: '资源图片',
      },
      {
        key: '/admin/imageCrawler',
        label: '图片采集',
        title: '图片采集',
      },
      {
        key: '/feedback-manage',
        label: '用户反馈',
        title: '用户反馈',
      },
      {
        key: '/admin/monitor',
        label: '系统监控',
        title: '系统监控',
      },
    ]

    // 未登录用户只能看到首页
    if (!loginUserStore.loginUser.id) {
      return [baseItems[0]]
    }

    return isAdmin ? [...baseItems, ...adminItems] : baseItems
  })

  const router = useRouter()
  //路由跳转事件
  const doMenuClick = ({ key }: { key: string }) => {
    console.log('Menu clicked:', key) // 添加日志
    router
      .push({
        path: key,
        replace: false,
      })
      .catch(err => {
        console.error('Navigation error:', err)
      })
  }

  // 选中项
  const current = ref<string[]>(['/'])

  // 退出登录
  const handleLogout = () => {
    userLogoutUsingPost1()
      .then(res => {
        if (res.data.code === 200) {
          // 退出成功
          // 重置用户状态为初始值
          loginUserStore.setLoginUser({
            id: 0,
            userName: '',
            userAccount: '',
            userAvatar: '',
            userRole: '',
            createTime: '',
            updateTime: '',
            isForbid: '',
            userProfile: '',
          })
          // 清除浏览器缓存
          localStorage.clear() // 清除本地存储
          sessionStorage.clear() // 清除会话存储
          message.success('退出成功')
          // 跳转到首页
          router.push({
            path: '/', // 跳转到首页
            replace: true, // 替换当前路由
          })
        } else {
          // 退出失败
          message.error(res.data.message || '退出失败')
        }
      })
      .catch(error => {
        // 请求异常
        message.error('退出失败: ' + error.data.message)
      })
  }

  // 注销账号
  const handleDeleteAccount = () => {
    message.warning('注销账号功能开发中')
  }
</script>

<style scoped>
  #globalHeader .title-bar {
    /* 让整体下移一点点 */
    margin-top: 10px;
    display: flex;
    align-items: center;
  }

  .weather-col {
    display: flex;
    align-items: center;
    /* 让整体下移一点点 */
    top: 7px;
    justify-content: center;
    /* 文字大小 */
    size: 33px;
  }

  .weather-theme-container {
    display: flex;
    align-items: center;
    gap: 0px;
    justify-content: center;
    flex-wrap: nowrap;
  }

  .theme-col {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
  }

  .menu-bar {
    margin-top: 10px;
  }

  .login-button {
    margin-top: 20px;
  }

  .title {
    color: var(--theme-text); /* 字体颜色 */
    font-size: 18px; /* 字体大小 */
    margin-left: 8px; /* 字体与图标之间的间距 */
    transition: color 0.3s ease;
  }

  .logo {
    height: 48px;
  }

  .avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    margin-left: 8px;
    cursor: pointer;
  }

  .user-info {
    display: flex;
    color: var(--theme-primary);
    align-items: center;
    /* 字体大小 */
    font-size: 14px;
    /* 不换行 */
    white-space: nowrap;
    /* 字体样式 */
    font-weight: 500;
    /* 让字体稍微下移 */
    margin-top: 10px;
    /* 确保有足够空间 */
    padding-right: 80px;
    transition: color 0.3s ease;
  }

  .avatar {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    margin-left: 8px;
  }

  .user-info {
    display: flex;
    color: #1890ff;
    align-items: center;
    font-size: 18px;
    /* 不换行 */
    white-space: nowrap;
    /* 字体样式 */
    font-weight: 500;
  }

  :deep(.ant-dropdown-menu-item) {
    white-space: nowrap; /* 强制单行显示 */
    padding: 8px 16px; /* 统一padding */
    height: 40px; /* 固定高度 */
    line-height: 24px; /* 固定行高 */
    display: flex; /* 使用flex布局 */
    align-items: center; /* 垂直居中 */
    gap: 8px; /* 图标和文字的间距 */
  }

  :deep(.ant-dropdown-menu) {
    min-width: 160px; /* 设置最小宽度 */
  }

  :deep(.ant-dropdown-menu-item .anticon) {
    font-size: 16px; /* 统一图标大小 */
  }
</style>
